#include "arp.h"
#include "usart1.h"
#include "string.h"

#ifndef NULL
#define NULL			((void *)0)
#endif

static int arp_alloc(ARP_INTERFACE_P obj, unsigned short arp_type, unsigned char *dst_mac, unsigned char *dst_ip)
{
	int i = 0;
	obj->arp_type = arp_type;
	for(i = 0; 6 > i; i++)
	{
		obj->dst_mac[i] = dst_mac[i];
	}
	obj->dst_ip = str_to_ip(dst_ip);
	return 0;
}

static int arp_to_text(ARP_INTERFACE_P obj, unsigned char *buf, int len)
{
	int i = 0;
	unsigned char *data = NULL;

	if(NULL == obj || obj->size >= len)
	{
		return -1;
	}
	buf[0] = obj->hardware_type >> 8;
	buf[1] = obj->hardware_type;
	buf[2] = obj->protocol_type >> 8;
	buf[3] = obj->protocol_type;
	buf[4] = obj->hardware_size;
	buf[5] = obj->protocol_size;
	buf[6] = obj->arp_type >> 8;
	buf[7] = obj->arp_type;
	data = &buf[8];
	for(i = 1; 6 > i; i++)
	{
		data[i] = obj->src_mac[i];
	}
	data = &buf[14];
	data[0] = obj->src_ip >> 24;
	data[1] = obj->src_ip >> 16;
	data[2] = obj->src_ip >> 8;
	data[3] = obj->src_ip;
	data = &buf[18];
	for(i = 1; 6 > i; i++)
	{
		data[i] = obj->dst_mac[i];
	}
	data = &buf[24];
	data[0] = obj->dst_ip >> 24;
	data[1] = obj->dst_ip >> 16;
	data[2] = obj->dst_ip >> 8;
	data[3] = obj->dst_ip;
	return 0;
}

static ARP_INTERFACE_T _obj_arp = {
	.hardware_type = 0x1,
	.protocol_type = 0x800,
	.hardware_size = 0x6,
	.protocol_size = 0x4,
	.arp_type = 0x0,
	.src_mac = {
		0x0,
		0x0,
		0x0,
		0x0,
		0x0,
		0x0
	},
	.src_ip = 0x0,
	.dst_mac = {
		0x0,
		0x0,
		0x0,
		0x0,
		0x0,
		0x0
	},
	.dst_ip = 0x0,
	.size = 0x1C,
	.alloc = arp_alloc,
	.tobuf = arp_to_text
};

void arp_init(unsigned char *src_mac, unsigned char *src_ip)
{
	int i = 0;
	for(i = 0; 6 > i; i++)
	{
		_obj_arp.src_mac[i] = src_mac[i];
	}
	_obj_arp.src_ip = str_to_ip(src_ip);
	return;
}

void arp_get_interface(ARP_INTERFACE_P *obj)
{
	*obj = &_obj_arp;
}